package com.qh.physicsexperiment.service;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
//    @Autowired
//    private UserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        拿到当前用户的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
//给当前用户设置权限，该权限是从用户数据库里查出来 的权限
//        System.out.println(currentUser.getPerms());
//        增加授权 权限应该放在数据库 perms字段 user:add
//        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //        只要登录就会走这个方法
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        User user = userService.selectByname(usernamePasswordToken.getUsername());
        if(user==null){
            return null;//抛出异常 UnknownAccountException
        }
        String password = user.getPassword();
//        密码比对shiro做  可以加密
//        第一个参数是将ueser放入里面subject
        return new SimpleAuthenticationInfo(user,password,"");
    }
}
